package org.boulderfoodrescue.webapp.server.viewer;

import java.util.LinkedList;
import java.util.List;

import org.boulderfoodrescue.webapp.client.old.viewer.ViewerService;
import org.boulderfoodrescue.webapp.shared.Place;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class ViewerServiceImpl extends RemoteServiceServlet implements ViewerService{
  @Override
  public Long savePlace(Place place) { 
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if(user == null){
      return null;
    }
    Long result;
    if(place.getKey() == null){
      place.setUsername(user.getEmail());
      result = Database.addPlace(place).getKey();
    }
    else
    {
      result = place.getKey();
      Database.updatePlace(place);
    }
    return result;
  }

  @Override
  public List<Long> savePlaces(List<Place> places) {
    List<Long> keys = new LinkedList<Long>();
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if(user == null)
      return null;
    String username = user.getEmail();
    Long result;
    for(Place place: places){
      if(place.getKey() == null)
      {
        place.setUsername(username);
        result = Database.addPlace(place).getKey();
      }
      else
      {
        result = place.getKey();
        Database.updatePlace(place);
      }
      keys.add(result);
    }
    return keys;
  }

  @Override
  public List<Place> getPlaces() {
    List<Place> places;
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if(user == null)
      return null;
    places = Database.getPlaceForUser(user.getEmail());
    return places;
  }

  @Override
  public List<Place> getAllPlaces() {
    return Database.getAllPlaces();
  }

  @Override
  public Boolean removePlace(Place place) {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if(user == null)
      return false;
    Database.removePlace(place);
    return true;
  }

}
